<template>
  <div id="employee-stats">
    <div ref="chart" id="chart" style="width: 100%; height: 600px; position: relative;"></div>
    <div id="controls" >
      <el-button type="primary" @click="huandquary(1)">近一个月</el-button>
      <el-button type="primary" @click="huandquary(3)">近三个月</el-button>
      <el-button type="primary" @click="huandquary(12)">近一年</el-button>
      <el-button type="primary" @click="huandquary(24)">近两年</el-button>
      <el-button type="primary" @click="huandquary(36)">近三年</el-button>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getEmpOpsApi } from '@/api/Empment/DataStatistics';

let options = {
  title: {
    text: '入职离职统计',
    left: 'left'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      animation: false
    }
  },
  legend: {
    data: ['离职员工', '新增员工']
  },
  toolbox: {
    feature: {
      dataZoom: {
        yAxisIndex: 'none'
      },
      restore: {},
      saveAsImage: {}
    }
  },
  axisPointer: {
    link: [
      {
        xAxisIndex: 'all'
      }
    ]
  },
  dataZoom: [
    {
      show: true,
      realtime: true,
      start: 30,
      end: 70,
      xAxisIndex: [0, 1]
    },
    {
      type: 'inside',
      realtime: true,
      start: 30,
      end: 70,
      xAxisIndex: [0, 1]
    }
  ],
  grid: [
    {
      left: 60,
      right: 50,
      height: '35%'
    },
    {
      left: 60,
      right: 50,
      top: '55%',
      height: '35%'
    }
  ],
  xAxis: [
    {
      type: 'time',
      boundaryGap: false,
      axisLine: {
        onZero: true
      },
      max: new Date(),
      axisLabel: {
        formatter: function (value, index) {
          return echarts.format.formatTime('yyyy-MM-dd', value);
        }
      },
      axisTick: {
        alignWithLabel: true
      },
      position: 'bottom'
    },
    {
      gridIndex: 1,
      type: 'time',
      boundaryGap: false,
      axisLine: {
        onZero: true
      },
      max: new Date(),
      axisLabel: {
        formatter: function (value, index) {
          return echarts.format.formatTime('yyyy-MM-dd', value);
        }
      },
      axisTick: {
        alignWithLabel: true
      },
      position: 'top'
    }
  ],
  yAxis: [
    {
      name: '入职人数/人',
      type: 'value',
      max: function (value) {
        return value.max + 10;
      }
    },
    {
      gridIndex: 1,
      name: '离职人数/人',
      type: 'value',
      inverse: true
    }
  ],
  series: [
    {
      name: '新增员工',
      type: 'line',
      smooth: true,
      symbolSize: 10,
      data: []
    },
    {
      name: '离职员工',
      type: 'line',
      xAxisIndex: 1,
      yAxisIndex: 1,
      smooth: true,
      symbolSize: 10,
      data: []
    }
  ]
};

export default {
  data() {
    return {
      chart: null,
      range: 1 // 默认值
    };
  },
  created() {
    this.fetchInitialData();
  },
  mounted() {
    this.chart = echarts.init(this.$refs.chart);
    this.fetchInitialData();
  },
  methods: {
    fetchInitialData() {
      this.huandquary(this.range);
    },
    huandquary(range) {
      this.range = range; // 更新范围
      this.updateXAxisRange();
      getEmpOpsApi(range).then(response => {
        this.createChart(response.data);
      }).catch(error => {
        console.error('Error fetching employee stats:', error);
      });
    },
    updateXAxisRange() {
      const now = new Date();
      const minDate = new Date(now.setMonth(now.getMonth() - this.range));
      options.xAxis[0].min = minDate;
      options.xAxis[1].min = minDate;
      if (this.chart) {
        this.chart.setOption(options);
      }
    },
    createChart(data) {
      // 确保 data 不为空
      if (!Array.isArray(data)) {
        console.error('Invalid data structure:', data);
        return;
      }

      const formattedOperationTime = [];
      const countIn = [];
      const countOut = [];

      data.forEach(item => {
        formattedOperationTime.push(item.formattedOperationTime);
        countIn.push(item.countIn);
        countOut.push(item.countOut);
      });

      options.series[0].data = formattedOperationTime.map((date, index) => [new Date(date), countIn[index]]);
      options.series[1].data = formattedOperationTime.map((date, index) => [new Date(date), countOut[index]]);

      this.chart.setOption(options);

      // 添加 resize 事件监听器，并在组件销毁时移除
      const resizeHandler = () => {
        this.chart.resize();
      };
      window.addEventListener('resize', resizeHandler);

      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', resizeHandler);
      });
    }
  }
};
</script>
